package com.sg.interceptor;

import com.sg.vo.BusinessVO;
import com.sg.vo.UserVO;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * @author wangcf
 * @Description 登录拦截器
 * @date 2023/3/9 14:48
 */
public class LoginStatedInterceptor implements HandlerInterceptor {

    Logger logger=Logger.getLogger(LoginStatedInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        logger.info("进入登录拦截器了");
        HttpSession session = httpServletRequest.getSession();
        Object obj = session.getAttribute("createUser");
        Object obj1=session.getAttribute("business");
        //判断session里面是否有对象
        if (obj != null||obj1!=null) {
            logger.info("登录进去了");
            return true;
        } else {
            //通过拦截器跳转到指定的页面中，通常是我们的首页，或者是登录的页面
            logger.info("未登陆成功");
            logger.info(httpServletRequest.getContextPath());
            httpServletResponse.setContentType("text/html");
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/index.action");
            //PrintWriter printWriter=httpServletResponse.getWriter();
            //printWriter.print("<script>alert('请先登录，请登录账号');location.href='../tologin.action'</script>");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
